import { create } from 'zustand';
import { persist } from 'zustand/middleware';
import { AuthState, LoginCredentials, User } from '@/types/auth';
import { authApi } from '@/lib/api/auth';
import { getCookie, setCookie, deleteCookie } from 'cookies-next';
import { isTokenExpired, parseJwt } from '@/lib/auth/jwt';

interface AuthStore extends AuthState {
  login: (credentials: LoginCredentials) => Promise<void>;
  register: (data: any) => Promise<void>;
  logout: () => Promise<void>;
  checkAuth: () => Promise<boolean>;
  setUser: (user: User | null) => void;
  setToken: (token: string | null) => void;
  setLoading: (isLoading: boolean) => void;
}

export const useAuthStore = create<AuthStore>()(
  persist(
    (set, get) => ({
      user: null,
      token: null,
      isAuthenticated: false,
      isLoading: true,

      setUser: (user: User | null) => set({ user }),
      setToken: (token: string | null) => set({ token }),
      setLoading: (isLoading: boolean) => set({ isLoading }),

      login: async (credentials: LoginCredentials) => {
        try {
          set({ isLoading: true });
          const { data } = await authApi.login(credentials);
          const { user, token } = data;
          
          set({ 
            user,
            token,
            isAuthenticated: true,
          });

          // 存储 token 到 cookie 中
          setCookie('auth-token', token, { 
            maxAge: credentials.remember ? 30 * 24 * 60 * 60 : 24 * 60 * 60,
            path: '/',
          });
        } catch (error) {
          console.error('登录失败', error);
          throw error;
        } finally {
          set({ isLoading: false });
        }
      },

      register: async (data) => {
        try {
          set({ isLoading: true });
          const response = await authApi.register(data);
          const { user, token } = response.data;
          
          set({ 
            user,
            token,
            isAuthenticated: true,
          });

          // 存储 token 到 cookie 中
          setCookie('auth-token', token, { 
            maxAge: 24 * 60 * 60,
            path: '/',
          });
        } catch (error) {
          console.error('注册失败', error);
          throw error;
        } finally {
          set({ isLoading: false });
        }
      },

      logout: async () => {
        try {
          set({ isLoading: true });
          try {
            // 尝试调用登出API，但即使失败也继续后续操作
            await authApi.logout();
          } catch (error) {
            console.error('退出登录API调用出错', error);
          }
        } finally {
          // 清除认证状态
          set({ 
            user: null,
            token: null,
            isAuthenticated: false,
            isLoading: false,
          });
          
          // 清除 cookie
          deleteCookie('auth-token');
          deleteCookie('refresh-token');
        }
      },

      checkAuth: async () => {
        try {
          // 如果已经处于认证状态且有用户信息，不再进行检查
          if (get().isAuthenticated && get().user) {
            set({ isLoading: false });
            return true;
          }
          
          set({ isLoading: true });
          
          // 检查本地 token
          const token = getCookie('auth-token') as string | undefined;
          
          if (!token) {
            set({ 
              user: null,
              token: null,
              isAuthenticated: false,
              isLoading: false,
            });
            return false;
          }
          
          // 检查 token 是否过期
          if (isTokenExpired(token)) {
            set({ 
              user: null,
              token: null,
              isAuthenticated: false,
              isLoading: false,
            });
            deleteCookie('auth-token');
            return false;
          }
          
          // 从 token 获取用户信息
          const payload = parseJwt(token);
          
          if (!payload) {
            set({ 
              user: null,
              token: null,
              isAuthenticated: false,
              isLoading: false,
            });
            deleteCookie('auth-token');
            return false;
          }
          
          try {
            // 尝试调用 API 获取最新用户信息，但不要长时间等待
            const timeoutPromise = new Promise((_, reject) => 
              setTimeout(() => reject(new Error('API请求超时')), 3000)
            );
            
            const { data } = await Promise.race([
              authApi.getMe(),
              timeoutPromise
            ]) as { data: any };
            
            set({ 
              user: data.user,
              token,
              isAuthenticated: true,
              isLoading: false,
            });
            return true;
          } catch (error) {
            console.log('获取用户信息失败，使用token中的信息', error);
            // API 请求失败，使用 token 中的信息
            const user: User = {
              id: payload.sub,
              email: payload.email,
              name: payload.name,
              role: payload.role,
            };
            
            set({ 
              user,
              token,
              isAuthenticated: true,
              isLoading: false,
            });
            return true;
          }
        } catch (error) {
          console.error('验证会话出错', error);
          set({ 
            user: null,
            token: null,
            isAuthenticated: false,
            isLoading: false,
          });
          return false;
        }
      },
    }),
    {
      name: 'auth-storage',
      partialize: (state) => ({ user: state.user, token: state.token }),
    }
  )
); 